package gods.bubble.server;

import gods.bubble.util.Config;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class BubbleServerSocket extends ServerSocket {
	public BubbleServerSocket(int port) throws IOException {
		super(port);
	}

	public static void main(String[] args) throws Exception {

		int port = Config.port;
		ServerSocket server = new BubbleServerSocket(port);
		System.out.println(new Date()
				+ " - BubbleServerSocket begins listening.");
		try {
			while (true) {
				new BubbleServerThread(server.accept()).start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		server.close();
	}
}

class BubbleServerThread extends Thread {
	private Socket client = null;
	private static SearchService ss = new SearchService();

	public BubbleServerThread(Socket s) throws IOException {
		client = s;
	}

	public void run() {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					client.getInputStream(), "utf8"));
			PrintWriter out = new PrintWriter(new OutputStreamWriter(
					client.getOutputStream(), "utf8"));

			String cmd = in.readLine();

			if (cmd.equals("Query")) {
				String query = in.readLine();
				int offset = Integer.valueOf(in.readLine());
				int limit = Integer.valueOf(in.readLine());
				int type = Integer.valueOf(in.readLine());

				System.out.println(new Date() + " -- Get query = " + query
						+ "; offset = " + offset + "; limit = " + limit
						+ "; type = " + type);
				String html = ss.search(query, offset, limit, type);

				out.println(html);
			}

			out.close();
			in.close();
			client.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
